//version 2021-03-17
$(document).ready(function () {
	/*页面rem单位初始化适应*/
	var html = $("html");
	var htmlfont = html.width() / 750 * 100 + "px";
	html.css("font-size", htmlfont);
	$(window).resize(function () {
		htmlfont = html.width() / 750 * 100 + "px";
		html.css("font-size", htmlfont);
	})

	/*解决键盘唤起遮挡问题*/
	$('body').on('focus','input,textarea',function () {
		var target = this;
		setTimeout(function () {
			target.scrollIntoViewIfNeeded();
		}, 500);
	});
	
	/*输入框获得焦点隐藏菜单*/
	$('body').on('focus','input[type="text"],input[type="number"],textarea',function(){
		$('nav').hide();
	})
	$('body').on('blur','input[type="text"],input[type="number"],textarea',function(){
		$('nav').show();
	})
	//修复ios input失焦时 输入键盘占页面问题
	if(/iPhone/.test(window.navigator.userAgent)) {
		$('body').on('blur',"input,select,textarea",function() {
			setTimeout(function() {          
				var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;          
				window.scrollTo(0, Math.max(scrollHeight, 0));     
			}, 100);
		})
	}
	/*修复ios select 不回弹*/
	var windowHeight = window.innerHeight;
	$('body').on('blur','select',function () {
	    var windowFocusHeight = window.innerHeight;
	    if (windowHeight == windowFocusHeight) {
	      return
	    }
	    console.log(windowHeight + '--' + windowFocusHeight);
	    console.log('修复');
	    var currentPosition;
	    var speed = 1; //页面滚动距离
	    currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
	    currentPosition -= speed;
	    window.scrollTo(0, currentPosition); //页面向上滚动
	    currentPosition += speed; //speed变量
	    window.scrollTo(0, currentPosition); //页面向下滚动
	 })
	
});


/*提示框组件*/
function alerttip(mes, type, callback, callback1) {
	//单键确认框 alerttip('内容','sure');
	if (type == 'sure') {
		$('body').append('<div class="sp-mask">'+
			'<div class="sp-alert sp-alert-bd">'+
				'<p>'+mes+'</p>'+
				'<div class="flex">'+
					'<div class="sp-alert-btn">好</div>'+
				'</div>'+
			'</div>'+
		'</div>');
		$('.sp-alert .sp-alert-btn').click(function (e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).parents('.sp-mask').fadeOut(300, function () {
				$(this).remove();
			})
			if (typeof (callback) == 'function') {
				callback();
			}
		})

	}
	//等待框 alerttip('内容','loading') 移除：$('.sp-loading').remove();
	else if(type=="loading"){
		$('body').append('<div class="sp-mask sp-loading">'+
			'<div class="sp-alert sp-alert-default sp-alert-loading">'+mes+'</div>'+
		'</div>');
	}
	//选择确认框 alerttip('内容','confirm',function(){//是运行的函数},function(){//否运行的函数})
	else if (type == 'confirm') {
		$('body').append('<div class="sp-mask">'+
			'<div class="sp-alert sp-alert-bd">'+
				'<p>'+mes+'</p>'+
				'<div class="flex">'+
					'<div class="sp-alert-btn" id="y">确定</div>'+
					'<div class="sp-alert-btn">取消</div>'+
				'</div>'+
			'</div>'+
		'</div>');
		$('.sp-alert .sp-alert-btn').click(function (e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).parents('.sp-mask').fadeOut(100, function () {
				$(this).remove();
			})
			if ($(this).attr('id') == 'y' && typeof (callback) == 'function') {
				callback();
			} else if (typeof (callback1) == 'function') {
				callback1();
			}
		})
	}
	//自动消失提示框 alerttip('内容')
	else {
		$('body').append('<div class="sp-mask">'+
			'<div class="sp-alert sp-alert-default">'+mes+
			'</div>'+
		'</div>');
		setTimeout(function () {
			$('.sp-mask').fadeOut(300, function () {
				$(this).remove();
			});
		}, 800);
	}
	setTimeout(function(){
		$('.sp-alert').addClass('sp-alert-animation');
	},50)
}

//获取链接参数
function getQueryString(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}
//js时间格式化
function formatTime(date){
	date = date || new Date();
	var y = date.getFullYear() , m = date.getMonth() + 1 , d = date.getDate();
	var h = date.getHours() , min = date.getMinutes();
	m = m < 10 ? '0' + m : m , d = d < 10 ? '0' + d : d
	h = h < 10 ? '0' + h : h , min = min < 10 ? '0' + min : min;
	var weekStr = {
		0:'日',
		1:'一',
		2:'二',
		3:'三',
		4:'四',
		5:'五',
		6:'六',
	};
	return {
		time:`${y}-${m}-${d} ${h}:${min}`,
		timeStr:`${y}年${m}月${d}日 ${h}:${min}`,
		date:`${y}-${m}-${d}`,
		year:y,
		month:m,
		week:date.getDay(),
		weekStr:weekStr[date.getDay()],
		day:d,
		hour:h,
		min:min,
		idTime:y.toString()+m.toString()+d.toString(),
	};
}
function rnd(n, m) {//返回包括n-m之间的随机数
	var random = Math.floor(Math.random() * (m - n + 1) + n);
	return random;
}

//禁用微信字体缩放
(function () {
　　if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
　　handleFontSize();
　　} else {
　　if (document.addEventListener) {
　　　　document.addEventListener("WeixinJSBridgeReady", handleFontSize, false);
　　} else if (document.attachEvent) {
　　　　document.attachEvent("WeixinJSBridgeReady", handleFontSize);
　　　　document.attachEvent("onWeixinJSBridgeReady", handleFontSize);
　　}
}
function handleFontSize() {
　　/*设置网页字体为默认大小*/
　　WeixinJSBridge.invoke('setFontSizeCallback', {
　　	'fontSize': 0
　　});
　　/*重写设置网页字体大小的事件*/
　　WeixinJSBridge.on('menu:setfont', function () {
　　　　WeixinJSBridge.invoke('setFontSizeCallback', {
　　　　　　'fontSize': 0
　　　　});
　　});
　　}
})();
//压缩图片
function compressImage(file,f) { 
	if(!file) return;
	// 压缩图片需要的一些元素和对象
	var reader = new FileReader(), img = new Image();
	// 缩放图片需要的canvas
	var canvas = document.createElement('canvas');
	var context = canvas.getContext('2d');
	// base64地址图片加载完毕后
	img.onload = function () {
		// 图片原始尺寸
		var originWidth = this.width;
		var originHeight = this.height;
		// 最大尺寸限制
		var maxWidth = 1000, maxHeight = 1000;
		// 目标尺寸
		var targetWidth = originWidth, targetHeight = originHeight;
		// 图片尺寸超过maxWidth x maxHeight的限制
		if (originWidth > maxWidth || originHeight > maxHeight) {
			if (originWidth / originHeight > maxWidth / maxHeight) {
				// 更宽，按照宽度限定尺寸
				targetWidth = maxWidth;
				targetHeight = Math.round(maxWidth * (originHeight / originWidth));
			} else {
				targetHeight = maxHeight;
				targetWidth = Math.round(maxHeight * (originWidth / originHeight));
			}
		}
			
		// canvas对图片进行缩放
		canvas.width = targetWidth;
		canvas.height = targetHeight;
		// 清除画布
		context.clearRect(0, 0, targetWidth, targetHeight);
		// 图片压缩
		context.drawImage(img, 0, 0, targetWidth, targetHeight);
		canvas.toBlob(function(d){
			typeof(f) == 'function' ? f({base64:canvas.toDataURL(),size:d.size / 1024 + 'kb',blob:d}) : '';
		})
	};
	reader.readAsDataURL(file);
	// 文件base64化，以便获知图片原始尺寸
	reader.onload = function(e) {
		img.src = e.target.result;
	};
}
//she接口请求
function sheApi(url,data,type){
	return new Promise(function(resolve,reject){
		if(!type){
			$.getJSON(url,data || {},function(d){
				if(d.Success){
					resolve(d.Data);
				}
				else{
					alert(d.ReturnValue);
				}
			}).fail(function(e){
				alerttip('网络错误');
			})
		}
		else{
			$.post(url,data || {},function(d){
				if(d.Success){
					resolve(d.Data);
				}
				else{
					alert(d.ReturnValue);
				}
			},'json').fail(function(e){
				alerttip('网络错误');
			})
		}
	})
	
}

/* Vue组件 */
//window 列表滚动加载组件
Vue.component('scroll-list',{
	props:{
		list:Array,
		pi:{
			type:Number,
			default:1,
		},
		ps:{
			type:Number,
			default:10
		},
		load:{
			type:Boolean,
			default:true
		},
		noDataTip:{
			type:String,
			default:'没有数据'
		},
		noMoreDataTip:{
			type:String,
			default:'没有更多数据了'
		}
	},
	data:function(){
		return {
			pageIndex:this.pi,
			scroll:true,
			bottomTip:''
		}
	},
	watch:{
		list:function(val,oldVal){
			if(val.length == oldVal.length && this.pageIndex == 1){
				this.scroll = false;
				this.bottomTip = this.noDataTip;
				return;
			}
			if(val.length == 0 && val.length < oldVal.length){//外部list清空 从第一页开始加载（外部加载）
				this.pageIndex = 1 , this.scroll = true;
				return;
			}
			
			if(val.length - oldVal.length == this.ps){//新增数量 = 一页加载数量
				this.scroll = true;
				this.bottomTip = '';
			}
			else{
				this.scroll = false;
				this.bottomTip = this.noMoreDataTip;
			}
		},
		load:function(val){
			val ? this.$emit('load',this.pageIndex,this.ps) : '';
		}
	},
	template:`<div>
				<slot v-for="(item,index) in list" :item="item" :index="index"></slot>
				<div class="bottom-tip">{{bottomTip}}</div>
			</div>`,
	created:function(){
		this.load ? this.$emit('load',this.pageIndex,this.ps) : '';
		var _this = this;
		window.addEventListener('scroll',function(){
			var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
			if(document.documentElement.scrollHeight <= document.documentElement.clientHeight + scrollTop + 50 && _this.scroll && _this.load){
				_this.bottomTip = '加载中', _this.pageIndex ++ , _this.scroll = false;
				_this.$emit('load',_this.pageIndex,_this.ps);
			}
		})
	}
})
//遮罩层组件
Vue.component('g-mask', {
  props: ['active','close'],
  template: `<div>
				  <transition enter-active-class="fadeIn" leave-active-class="fadeOut">
					<div class="mask flex animated" v-if="active"></div>
				  </transition>
				<transition enter-active-class="slideInDown" leave-active-class="slideOutUp">
					<div class="card-box flex animated" v-if="active">
						<div class="card">
							<slot></slot>
						</div>
						<i v-if="_events.close" class="glyphicon glyphicon-remove-circle" @click="$emit('close')"></i>
					</div>
				</transition>
			</div>`
})
//输入框组件
Vue.component('sp-input',{
	model: {
	    prop:'value',
	    event: 'input'
	},
	props:{
		type:{
			default:'text'
		},
		value:String,
		placeholder:{
			default:''
		}
	},
	template:`<div class="input-fill-x">
				<input class="input-fill" :type="type" :placeholder="placeholder" :value="value" @input="$emit('input',$event.target.value)">
				<label class="input-label">{{placeholder}}</label>
			</div>`,
	
})
